﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace S_Incident.Infrasturctre
{
    public class BaceRepository<T> : IRepository<T> where T : class, new()
    {
        private readonly ISqlSugarClient sqlSugarClient;
        public BaceRepository(ISqlSugarClient sqlSugarClient)
        {
            this.sqlSugarClient = sqlSugarClient;
        }
        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(T model)
        {
            var res = await sqlSugarClient.Insertable(model).ExecuteCommandAsync();
            return res;
        }
        /// <summary>
        /// 批量新增
        /// </summary>
        /// <param name="models"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(List<T> models)
        {
            var res = await sqlSugarClient.Insertable(models).ExecuteCommandAsync();
            return res;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>

        public async Task<int> DeleteAsync(T t)
        {
            var res = await sqlSugarClient.Deleteable(t).ExecuteCommandAsync();
            return res;
        }
        /// <summary>
        /// 查询带条件
        /// </summary>
        /// <param name="expre"></param>
        /// <returns></returns>
        public async Task<List<T>> GetAsync(Expression<Func<T, bool>> expre)
        {
            var res = await sqlSugarClient.Queryable<T>().Where(expre).ToListAsync();
            return res;
        }

        /// <summary>
        /// 单个查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<T> GetFindAsync(int id)
        {
            return await sqlSugarClient.Queryable<T>().InSingleAsync(id);
        }
        /// <summary>
        /// 通过条件找到对应实体单条数据
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <returns>单条数据</returns>
        public async Task<T> GetModelAsync(Expression<Func<T, bool>> expression)
        {
            return await sqlSugarClient.Queryable<T>().FirstAsync(expression);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(T model)
        {
            var res = await sqlSugarClient.Updateable(model).ExecuteCommandAsync();
            return res;
        }
    }
}
